import { Cookies } from 'quasar'

import { saveToken, TOKEN, SESSION, EXPIRES, USER } from '../utils/auth'

export const authMixin = {
  methods: {
    authorize ({ user, token, webdog, session = true }) {
      if (webdog === 'ageeye') {
        user.admin = true
      }

      saveToken(token, user, session)

      token = 'ageeye ' + token
      user.token = token

      this.$store.commit('setAuth', user)
    },
    quit () {
      this.getRequest({
        api: '/api/user/logout/'
      })

      // if (status !== 200){
      //   this.notify('error', '退出时发生错误，请重试')
      //   return
      // }

      this.$store.commit('quit')

      const path = this.$route.path

      if (path.match(/^\/account/)) {
        this.$router.push('/login')
      }
    },
    async refreshToken () {
      const token = Cookies.get(TOKEN)
      const session = Cookies.get(SESSION)

      if (this.auth || !session) {
        return false
      }

      const { status, data } = await this.postRequest({
        api: '/api-token-refresh/',
        data: {
          token
        }
      })

      if (status === 200) {
        this.authorize(data)
      } else {
        this.$store.quit()
      }
    },
    updateCookieUser () {
      let expires = Cookies.get(EXPIRES)

      if (expires) {
        expires = new Date(expires)

        const user = this.auth
        delete user.token

        Cookies.set(USER, user, {
          path: '/',
          expires
        })
      }
    }
  }
}
